package o2o.web.actions.order.postman;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jinyou.utils.common.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import lombok.extern.slf4j.Slf4j;
import o2o.business.device.AppDeviceInfoBusiness;
import o2o.cache.agent.PostmanAgentRelationMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.order.*;
import o2o.cache.order.admin.AgentOrderMemoryMan;
import o2o.cache.order.admin.CityOrderMemoryMan;
import o2o.cache.order.postman.PostmanOrderMemoryMan;
import o2o.cache.order.postman.PostmanOrderMemoryMan2;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanOnlineMemory;
import o2o.cache.postman.PostmanShopRelationMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.company.postman.PostCompanyInfo;
import o2o.dao.PO.company.postman.PostmanSignCompanyInfo;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.POSTMAN_TYPE;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.order.*;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.postman.mapper.CityPostmanMapper;
import o2o.system.data.POSTMAN_IN_CITY_OR_AGENT_DATA;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.system.data.SYS_SETTINGS;
import o2o.system.data.SYS_SOS_MODEL_TYPE;
import o2o.task.order.OrderBakTaskUtils;
import o2o.utils.CommonUtils;
import o2o.web.actions.company.postman.PostCompanyMan;
import o2o.web.actions.order.OrderListMan;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.order.user.UserOrderMan;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

//配送员订单列表管理
@Api(tags = "配送员订单列表管理")
@Controller
@Slf4j
public class PostmanOrderListController {

    @Autowired
    private CityPostmanMapper cityPostmanMapper;

    //----------------------------配送员
    /**
     * 配送员获取最新订单
     */
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/new/list")
    @ResponseBody
    public String order_postman_new_list(String token, Integer orderType,
                                         String devJson,// 设备信息
                                         Long createTime, Integer page, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        } else {
            // 设置骑手在线
            PostmanOnlineMemory.getInstance().add(postman.getUsername());
            if (ValidateUtil.isNotNull(devJson)) {
                // 处理设备信息
                AppDeviceInfoBusiness.postmanAddDevice(postman.getUsername(), devJson);
            }
        }
        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法接单");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        //是否为加载更多，0不是，1是
        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 0;
        }

        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }


        //获取配送员所有未接订单
        List<OrderInfo> list = PostmanOrderMemoryMan.listOfPostmanNew(user.getUsername(), createTime, isLoadMore);
        if (ValidateUtil.isAbsList(list)) {
            // 分页判断
            long totalCount = 0;
            List<OrderInfo> newList = null;
            if (ValidateUtil.isNotAbsInteger(page)) {
//                newList = list.subList(0, size - 1);
                if (list.size() > size) {
                    newList = list.subList(0, size - 1);
                } else {
                    newList = list;
                }
            } else {
                // 分页
                JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                newList = (List<OrderInfo>) pageList.list;
                totalCount = pageList.totalCount;
            }
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < newList.size(); i++) {
                if (null == newList.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = null;
                if (SYS_SETTINGS.HAS_MULTIPLE_ORDER == 1 && OrderMan.isMultipleParentOrder(newList.get(i))) {
                    orderInfoVO = OrderMan.getMultipleParentOrderDetail(newList.get(i).getOrderNo(), user);
                    if (null == orderInfoVO) {
                        continue;
                    }
                } else {
                    orderInfoVO = new OrderInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(newList.get(i), orderInfoVO, null);
                    } catch (Exception e) {
                        log.info("对象属性复制出错，原因==>{}",e.getMessage());
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoVO) {
                        continue;
                    }
                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != 1 && null != orderInfoVO.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
                        List<OrderGoodsLabelVO> labels = OrderListMan.listOfOrderNO(orderInfoVO.getOrderNo());
                        orderInfoVO.setLabelList(labels);
                    }

                }
                //添加商品列表
                orderInfoVO.setGoodsList(OrderMan.getGoodListByOrderNo(orderInfoVO.getOrderNo()));
                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList, totalCount);
            }
        }

        // 订单模式 在抢单之前判断订单模式
        // 若是仅调度模式 将不能看见商圈内的新订单
        /*if (SYS_SETTINGS.ADMIN_MANAGER_GRAB_ORDER_MODE == 0 && SYS_SETTINGS.GRAB_ORDER_MODE != null && GRAB_ORDER_MODE.ONLY_DISPATCH_MODE == SYS_SETTINGS.GRAB_ORDER_MODE) {
            return AjaxResult.successResult(0, null);
        }*/

        //无最新指定订单，返回待抢订单
        List<OrderInfo> orderList = null;
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        Set<Long> companyIdSet = null;
        if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
            companyIdSet = PostCompanyMan.listCompanyIdSetByPostman(cityPostman.getUsername(), cityPostman.getType());
            if (companyIdSet != null && !companyIdSet.isEmpty()) {
                // Set<Integer> orderTypeSet = OrderTypeMemory.getInstance().listOfPostmanTypeByOrderType(postman.getType());
                Set<Integer> postTypeSet = new HashSet<>();
                postTypeSet.add(cityPostman.getType());
                Set<Integer> orderTypeSet = OrderTypeMemory.getInstance().listOfOrderTypeByPostType(postman.getType());
                orderList = CityOrderMemoryMan.cityUnDeliveryByCompanyIdList(cityPostman.getCity(), createTime, size, isLoadMore, orderTypeSet, postTypeSet, companyIdSet, cityPostman.getUsername());
            }
            if (companyIdSet == null) {
                companyIdSet = Collections.EMPTY_SET;
            }
        }
        if (null != cityPostman && companyIdSet == null) {
            //获取该城市订单
//            List<OrderInfo> orderList = null;

            // 是不是只能获取调度的订单
            boolean isDisPatchFirst = false;
            if (SYS_SETTINGS.ADMIN_MANAGER_GRAB_ORDER_MODE == 0 && SYS_SETTINGS.GRAB_ORDER_MODE == GRAB_ORDER_MODE.DISPATCH_FIRST_TO_OTHER) {
                isDisPatchFirst = true;
            }
            // 获取骑手服务的商家
            Set<Long> shopIdSet = null;
            if (SYS_SETTINGS.POSTMAN_SERVICE_SHOP == 1) {
                shopIdSet = PostmanShopRelationMemory.getInstance().getShopIdSetByPostmanUsername(cityPostman.getUsername());
                if (shopIdSet == null || shopIdSet.isEmpty()) {
                    shopIdSet = new HashSet<>();
                    shopIdSet.add(0L);
                }
            }
            //驻店骑手, 获取代抢订单
            if (cityPostman.getPostman_type() != null && cityPostman.getPostman_type() == 1) {
                orderList = CityOrderMemoryMan.cityUnDeliveryList(cityPostman.getCity(), cityPostman.getCounty(), cityPostman.getRegion(),
                        createTime, isLoadMore, orderType, cityPostman.getType(), cityPostman.getUsername(), false, shopIdSet);
            }
        }


        if (ValidateUtil.isAbsList(orderList)) {
            // 分页判断
            long totalCount = 0;
            List<OrderInfo> newList = null;
            if (ValidateUtil.isNotAbsInteger(page)) {
//                newList = orderList.subList(0, size - 1);
                if (orderList.size() > size) {
                    newList = orderList.subList(0, size - 1);
                } else {
                    newList = orderList;
                }
            } else {
                // 分页
                JYPageUtils.PageList pageList = JYPageUtils.getList(orderList, page, size);
                newList = (List<OrderInfo>) pageList.list;
                totalCount = pageList.totalCount;
            }

            List<OrderInfoVO> orderInfoVOList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < newList.size(); i++) {
                if (null == newList.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = null;
                if (SYS_SETTINGS.HAS_MULTIPLE_ORDER == 1) {
                    if (OrderMan.isMultipleParentOrder(newList.get(i))) {
                        orderInfoVO = OrderMan.getMultipleParentOrderDetail(newList.get(i).getOrderNo(), user);
                        if (null == orderInfoVO) {
                            continue;
                        }
                    } else {
                        orderInfoVO = new OrderInfoVO();
                        try {
                            ObjectUtils.copyPropertiesExclude(newList.get(i), orderInfoVO, null);
                        } catch (Exception e) {
                            log.info("对象属性复制出错，原因==>{}",e.getMessage());
                            e.printStackTrace();
                            continue;
                        }
                        if (null == orderInfoVO) {
                            continue;
                        }
                        if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                            orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                        }
                        if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != 1 && null != orderInfoVO.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
                            List<OrderGoodsLabelVO> labels = OrderListMan.listOfOrderNO(orderInfoVO.getOrderNo());
                            orderInfoVO.setLabelList(labels);
                        }
                    }
                } else {
                    orderInfoVO = new OrderInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(newList.get(i), orderInfoVO, null);
                    } catch (Exception e) {
                        log.info("对象属性复制出错，原因==>{}",e.getMessage());
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoVO) {
                        continue;
                    }
                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != 1 && null != orderInfoVO.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
                        List<OrderGoodsLabelVO> labels = OrderListMan.listOfOrderNO(orderInfoVO.getOrderNo());
                        orderInfoVO.setLabelList(labels);
                    }
                }

                orderInfoVOList.add(orderInfoVO);
            }
            return AjaxResult.successResult(orderInfoVOList, totalCount);
        }
        return AjaxResult.successResult(0, null);
    }

    //配送员已抢订单  包含自己抢的、管理员分配接受的、配送中，管理后台分配未接受的要排除
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/grab/list")
    @ResponseBody
    public String order_postman_new_grab_list(String token, Long createTime, String username, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //如果createTime是-1  是获取所有进行中订单
        if (null == createTime) {
            createTime = 0l;
        }

        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        //是否为加载更多，0不是，1是
        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 1;
        }

        if (ValidateUtil.isNull(username)) {
            username = user.getUsername();
        }


        //获取配送员所有已抢订单
        List<OrderInfo> list = PostmanOrderMemoryMan.listOfPostmanGrab(username, createTime, size, isLoadMore);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVerifyVO> voList = new ArrayList<OrderInfoVerifyVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVerifyVO orderInfoVO = null;
                if (SYS_SETTINGS.HAS_MULTIPLE_ORDER == 1 && OrderMan.isMultipleParentOrder(list.get(i))) {
                    orderInfoVO = OrderMan.getMultipleOrderDetail(list.get(i).getOrderNo(), user);
                    if (orderInfoVO != null) {
                        voList.add(orderInfoVO);
                    }
                } else {
                    orderInfoVO = new OrderInfoVerifyVO();
//                OrderInfoVerifyVO orderInfoVO = new OrderInfoVerifyVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoVO) {
                        continue;
                    }
                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
//                    orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    //  添加抢单配送公司信息
                    if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
                        if (orderInfoVO.getGrabCompanyId() != null) {
                            PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getById(orderInfoVO.getGrabCompanyId());
                            if (companyInfo != null) {
                                orderInfoVO.setGrabCompanyName(companyInfo.getCompanyName());
                            }
                        }
                    }
                    //服务单相关信息
                    if (null != orderInfoVO.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
                        //标签信息
                        List<OrderGoodsLabel> labelList = OrderGoodsLabelMemory.getInstance().listOfOrderNo(orderInfoVO.getOrderNo());
                        if (ValidateUtil.isAbsList(labelList)) {
                            List<OrderGoodsLabelVO> labelVOList = new ArrayList<>();
                            for (int j = 0; j < labelList.size(); j++) {
                                if (null == labelList.get(j)) {
                                    continue;
                                }
                                OrderGoodsLabelVO vo = new OrderGoodsLabelVO();
                                try {
                                    ObjectUtils.copyPropertiesExclude(labelList.get(j), vo, null);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    continue;
                                }
                                labelVOList.add(vo);
                            }
                            orderInfoVO.setLabelList(labelVOList);
                        }
                    }
                }
                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }


        return AjaxResult.successResult(0, null);
    }


    //配送员已抢待取货或者配送中的订单接口
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/wait-post/list")
    @ResponseBody
    public String order_postman_new_grab_wait_list(String token, Long createTime, String username, Integer size, Integer isLoadMore, Integer posting) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //如果createTime是-1  是获取所有进行中订单
        if (null == createTime) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        //是否为加载更多，0不是，1是
        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 1;
        }
        if (ValidateUtil.isNull(username)) {
            username = user.getUsername();
        }
        boolean isWait = true;
        if (posting != null && posting == 1) {
            isWait = false;
        }
        List<OrderInfo> list = PostmanOrderMemoryMan.listOfPostmanWaitOrPost(username, createTime, size, isLoadMore, isWait);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVerifyVO> voList = new ArrayList<OrderInfoVerifyVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVerifyVO orderInfoVO = null;
                if (SYS_SETTINGS.HAS_MULTIPLE_ORDER == 1 && OrderMan.isMultipleParentOrder(list.get(i))) {
                    orderInfoVO = OrderMan.getMultipleOrderDetail(list.get(i).getOrderNo(), user);
                    if (orderInfoVO != null) {
                        voList.add(orderInfoVO);
                    }
                } else {
                    orderInfoVO = new OrderInfoVerifyVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoVO) {
                        continue;
                    }
                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    //  添加抢单配送公司信息
                    if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
                        if (orderInfoVO.getGrabCompanyId() != null) {
                            PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getById(orderInfoVO.getGrabCompanyId());
                            if (companyInfo != null) {
                                orderInfoVO.setGrabCompanyName(companyInfo.getCompanyName());
                            }
                        }
                    }
                    //服务单相关信息
                    if (SYS_SETTINGS.CUSTOM_SYSTEM_TYPE != 1 && null != orderInfoVO.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
                        //标签信息
                        List<OrderGoodsLabel> labelList = OrderGoodsLabelMemory.getInstance().listOfOrderNo(orderInfoVO.getOrderNo());
                        if (ValidateUtil.isAbsList(labelList)) {
                            List<OrderGoodsLabelVO> labelVOList = new ArrayList<>();
                            for (int j = 0; j < labelList.size(); j++) {
                                if (null == labelList.get(j)) {
                                    continue;
                                }
                                OrderGoodsLabelVO vo = new OrderGoodsLabelVO();
                                try {
                                    ObjectUtils.copyPropertiesExclude(labelList.get(j), vo, null);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    continue;
                                }
                                labelVOList.add(vo);
                            }
                            orderInfoVO.setLabelList(labelVOList);
                        }
                    }
                    //获取商品列表
                    orderInfoVO.setGoodsList(OrderMan.getGoodListByOrderNo(orderInfoVO.getOrderNo()));
                    voList.add(orderInfoVO);
                }
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    //配送员已完成订单
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/finish/list")
    @ResponseBody
    public String order_postman_finish_list(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }

        //获取配送员所有已完成订单
        List<OrderInfo> list = PostmanOrderMemoryMan.listOfPostmanFinish(user.getUsername(), createTime, size);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = null;
                if (SYS_SETTINGS.HAS_MULTIPLE_ORDER == 1 && OrderMan.isMultipleParentOrder(list.get(i))) {
                    orderInfoVO = OrderMan.getMultipleParentOrderDetail(list.get(i).getOrderNo(), user);
                    if (null == orderInfoVO) {
                        continue;
                    }
                } else {
                    orderInfoVO = new OrderInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoVO) {
                        continue;
                    }

                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    //  添加抢单配送公司信息
                    if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
                        if (orderInfoVO.getGrabCompanyId() != null) {
                            PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getById(orderInfoVO.getGrabCompanyId());
                            if (companyInfo != null) {
                                orderInfoVO.setGrabCompanyName(companyInfo.getCompanyName());
                            }
                        }
                    }
                    //开锁订单显示收益
                    if (0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
                        OrderPayInfo payInfo = OrderPayMemory.getInstance().get(orderInfoVO.getOrderNo());
                        if (null != payInfo) {
                            orderInfoVO.setShopMoney(payInfo.getPostmanMoney());
                        }
                    }
                }
                voList.add(orderInfoVO);

//                try {
//                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//                if (null == orderInfoVO) {
//                    continue;
//                }
//
//                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
////                    orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
//                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
//                }
//                //  添加抢单配送公司信息
//                if (SYS_SETTINGS.THIRD_PARTY_COMPANY != null && SYS_SETTINGS.THIRD_PARTY_COMPANY == 1) {
//                    if (orderInfoVO.getGrabCompanyId() != null) {
//                        PostCompanyInfo companyInfo = PostCompanyMemory.getInstance().getById(orderInfoVO.getGrabCompanyId());
//                        if (companyInfo != null) {
//                            orderInfoVO.setGrabCompanyName(companyInfo.getCompanyName());
//                        }
//                    }
//                }
//                //开锁订单显示收益
//                if (0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
//                    OrderPayInfo payInfo = OrderPayMemory.getInstance().get(orderInfoVO.getOrderNo());
//                    if (null != payInfo) {
//                        orderInfoVO.setShopMoney(payInfo.getPostmanMoney());
//                    }
//                }
//                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, null);
    }

    // 配送员订单数量统计
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/counts")
    @ResponseBody
    public String order_postman_counts(String token, String username,
                                       Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("账号不能为空");
        }
//        if (!ValidateUtil.isAbsLong(startTime)) {
//            return AjaxResult.errorResult("开始时间不能为空");
//        }
//        if (!ValidateUtil.isAbsLong(endTime)) {
//            return AjaxResult.errorResult("结束时间不能为空");
//        }


        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }

        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);//所有未删除的
        expression.addChild("postmanusername", username);
        expression.addChild("ispaid", 1);
        expression.addChild("orderstatus", ORDER_STATUS.OVER);
        if (ValidateUtil.isAbsLong(startTime) && startTime > 0) {
            expression.addChild("createtime", ">=", startTime);
        }
        if (ValidateUtil.isAbsLong(endTime) && endTime > 0) {
            expression.addChild("createtime", "<=", endTime);
        }

        query.addCondition(expression);
        query.setPage(page);
        query.setSize(size);

        String sql = DaoUtils.getSql(PojoTables.OrderInfo, query);
        String sqlCount = DaoUtils.getSqlCount(PojoTables.OrderInfo, query);
        List<OrderInfo> list = null;
        Long totalCount = 0l;
        try {
            list = (List<OrderInfo>) UserDaoSql.getInstance().list(OrderInfo.class, sql);
            totalCount = UserDaoSql.getInstance().getCount(sqlCount);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后再试");
        }
        if (null == totalCount) {
            totalCount = 0l;
        }

        if (ValidateUtil.isAbsList(list)) {
            return AjaxResult.successResult(totalCount, list.size(), list);
        }
        return AjaxResult.successResult(0, 0, null);
    }

    // 配送员外卖、跑腿订单统计
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/statistical/list")
    @ResponseBody
    public String order_postman_finish_list_v2(String token, String city, String county, String username, Integer postmanType, Integer isExcel, String cityAdminUsername, Long agentId,
                                               Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
//            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        if (isExcel == null) {
            isExcel = 0;
        }
        String t_order_info = PojoTables.OrderInfo;
        String t_order_pay = PojoTables.OrderPay;
        if (null != SYS_SETTINGS.USE_BAK_ORDER && 0 == 1 - SYS_SETTINGS.USE_BAK_ORDER) {
            String dataDbName = OrderBakTaskUtils.getDataDbName();
            if (ValidateUtil.isNotNull(dataDbName)) {
                t_order_info = dataDbName + "." + PojoTables.D_ORDER_INFO;
                t_order_pay = dataDbName + "." + PojoTables.D_ORDER_PAY;
            }
        }


        StringBuffer sb = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        sb.append("select m.username,m.type,IFNULL(t.wmCount,0) wmCount1,IFNULL(t.wmCost,0) wmCost1, IFNULL(t2.wmCount,0) wmCount2,IFNULL(t2.wmCost,0) wmCost2,(IFNULL(t.wmCount, 0)+IFNULL(t2.wmCount, 0)) wmCount," +
                " (IFNULL(t.wmCost, 0)+IFNULL(t2.wmCost, 0)) wmCost," +
                " IFNULL(f.ptCount,0) ptCount,IFNULL(f.ptCost,0) ptCost, ");
        // y一乙系统有配送公司
        if (Optional.ofNullable(SYS_SETTINGS.CUSTOM_SYSTEM_TYPE).orElse(0) == 1) {
            sb.append(" IFNULL(s.squareCount, 0) squareCount ,  IFNULL(s.squareCost, 0) squareCost ,");
        }
        sb.append(" IFNULL(p.isPost,0) isPost,IFNULL(c.isTrouble,0) isTrouble,IFNULL(commH.haoping,0) haoping,IFNULL(commC.chaping,0) chaping from ").append(PojoTables.CityPostman)
                .append(" m ");
        // 外卖相关 - 一级骑手
        sb.append(" left join ( select a.postmanUsername, a.postmanName,count(a.orderNo) as wmCount, sum(b.postmanMoney) as wmCost from ")
                .append(t_order_info).append(" a Left join ").append(t_order_pay).append(" b on a.orderno=b.orderno where a.orderType = ").append(ORDER_TYPE.SHOP_GOODS).append(" and a.orderStatus = ").append(ORDER_STATUS.OVER);
        // 外卖下单时间在开始时间和结束时间之间
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" and a.delFlag = 0 group by a.postmanUsername) t on t.postmanUsername = m.username ");

        // 外卖相关 - 二级骑手
        sb.append(" left join ( select a.secondaryPostManUsername, count(a.orderNo) as wmCount, sum(b.secondaryPostmanMoney) as wmCost from ")
                .append(t_order_info).append(" a Left join ").append(t_order_pay).append(" b on a.orderno=b.orderno where a.orderType = ").append(ORDER_TYPE.SHOP_GOODS).append(" and a.orderStatus = ").append(ORDER_STATUS.OVER);
        // 外卖下单时间在开始时间和结束时间之间
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" and a.delFlag = 0 group by a.secondaryPostManUsername) t2 on t2.secondaryPostManUsername = m.username ");

        // 跑腿订单
        sb.append(" left join (select a.postmanUsername,a.postmanName,count(a.orderNo) as ptCount,sum(b.postmanMoney) as ptCost from ")
                // .append(PojoTables.OrderInfo).append(" a Left join ").append(PojoTables.OrderPay).append(" b on a.orderno=b.orderno  where a.orderType = ").append(ORDER_TYPE.PAO_TUI).append(" and a.orderStatus = ").append(ORDER_STATUS.OVER);
                // .append(t_order_info).append(" a Left join ").append(t_order_pay).append(" b on a.orderno=b.orderno  where a.orderType = ").append(ORDER_TYPE.PAO_TUI).append(" and a.orderStatus = ").append(ORDER_STATUS.OVER).append(" and  a.orderNo not like 'S%'");
                .append(t_order_info).append(" a Left join ").append(t_order_pay).append(" b on a.orderno=b.orderno  where a.orderType IN (").append(StringUtils.join(ORDER_TYPE.PAOTUI_TYPE_LIST, ",")).append(") and a.orderStatus = ").append(ORDER_STATUS.OVER).append(" and  a.orderNo not like 'S%'");
        // 跑腿下单时间在开始时间和结束时间之间
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" and a.delFlag = 0 group by a.postmanUsername) f  on m.username = f.postmanUsername ");

        // 创业商圈订单量问题 yangtk 2020年5月12日09:42:37
        if (Optional.ofNullable(SYS_SETTINGS.CUSTOM_SYSTEM_TYPE).orElse(0) == 1) {
            sb.append(" left join (select a.postmanUsername,a.postmanName,count(a.orderNo) as squareCount,sum(b.postmanMoney) as squareCost from ")
                    .append(t_order_info).append(" a Left join ").append(t_order_pay).append(" b on a.orderno=b.orderno  where a.orderType = ").append(ORDER_TYPE.SHOP_GOODS)
                    .append(" and a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.orderNo  LIKE 'P%' ");
            if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
                sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
            }
            sb.append(" and a.delFlag = 0 group by a.postmanUsername) s  on m.username = s.postmanUsername ");
        }
        // end

        // 添加超时量统计字段
        sb.append(" LEFT JOIN (SELECT a.postmanUsername,COUNT(1) AS isPost FROM ").append(t_order_info).append(" a WHERE ((a.agentPostmanOverTime > 0 and ((a.postmanFinishTime - a.createTime) > (a.agentPostmanOverTime * 60 * 1000))) or (a.ziQuTime>0 and a.postmanFinishTime > a.ziQuTime))  AND")
                // .append(" a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0");
                .append(" a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0").append(" and  a.orderNo not like 'S%'");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) p ON p.postmanUsername = m.username ");

        // 添加异常上报统计字段
        sb.append(" LEFT JOIN (SELECT a.postmanUsername, COUNT(1) AS isTrouble FROM ").append(t_order_info).append(" a ")
                // .append(" RIGHT JOIN ").append(PojoTables.ORDER_POSTMAN_TROUBLE).append(" b ON a.orderNo=b.orderNo WHERE a.orderStatus =  ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0");
                .append(" RIGHT JOIN ").append(PojoTables.ORDER_POSTMAN_TROUBLE).append(" b ON a.orderNo=b.orderNo WHERE a.orderStatus =  ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0").append(" and  a.orderNo not like 'S%'");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and b.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) c ON c.postmanUsername = m.username");

        // 好评数量
        sb.append(" LEFT JOIN (SELECT a.postmanUsername, COUNT(1) AS haoping FROM ").append(t_order_info)
                .append(" a LEFT JOIN ").append(PojoTables.ORDER_COMMENT).append(" b ON a.orderNO = b.orderNo ")
//                .append(" LEFT JOIN ").append(PojoTables.ShopInfo).append(" si ON a.shopId = si.id ")
                // .append(" WHERE a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0 AND b.delFlag = 0 and si.delFlag=0 and a.isRefundApply=0 and a.isPartCancelApply=0 AND b.star = 5 AND b.commentType = 2 ");
//                .append(" WHERE a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0 AND b.delFlag = 0 and si.delFlag=0 and a.isRefundApply=0 and a.isPartCancelApply=0 AND b.star = 5 AND b.commentType = 2 ").append(" and  a.orderNo not like 'S%'");
                .append(" WHERE a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0 AND b.delFlag = 0  and a.isRefundApply=0 and a.isPartCancelApply=0 AND b.star = 5 AND b.commentType = 2 ").append(" and  a.orderNo not like 'S%'");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) commH ")
                .append(" ON commH.postmanUsername = m.username");

        // 差评数量
        sb.append(" LEFT JOIN (SELECT a.postmanUsername, COUNT(1) AS chaping FROM ").append(t_order_info)
                .append(" a LEFT JOIN ").append(PojoTables.ORDER_COMMENT).append(" b ON a.orderNO = b.orderNo ")
                // .append(" WHERE a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0 AND b.delFlag = 0 AND b.star = 1 AND b.commentType = 2 ");
                .append(" WHERE a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0 AND b.delFlag = 0 AND b.star = 1 AND b.commentType = 2 ").append(" and  a.orderNo not like 'S%'");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) commC ")
                .append(" ON commC.postmanUsername = m.username");
        if (agentId != null || ValidateUtil.isNotNull(cityAdminUsername)) {
            sb.append(" LEFT JOIN ").append(PojoTables.POSTMAN_AGENT_RELATION).append(" par ON par.postmanUsername = m.username AND par.delFlag = 0 ");
            sb.append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" uar ON uar.agentId = par.agentId AND uar.delFlag = 0");
        }

//        sb.append(" LEFT JOIN ").append(PojoTables.POSTMAN_AGENT_RELATION).append(" par ON par.postmanUsername = m.username AND par.delFlag = 0 ");
//        sb.append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" uar ON uar.agentId = par.agentId AND uar.delFlag = 0");
        sb.append(" where m.delFlag = 0 ");
        if (null != postmanType && postmanType != 0) {
            sb.append(" and m.type=").append(postmanType).append(" ");
        }

        if (ValidateUtil.isNotNull(city)) {
            sb.append(" and m.city = '").append(city).append("'");
        }
        if (ValidateUtil.isNotNull(county)) {
            sb.append(" and m.county = '").append(county).append("'");
        }
        if (agentId != null) {
            sb.append(" and par.agentId = ").append(agentId);
        }
        if (ValidateUtil.isNotNull(cityAdminUsername)) {
            sb.append(" and uar.username = '").append(cityAdminUsername).append("' ");
        }

        if (ValidateUtil.isNotNull(username)) {
            sb.append(" and m.username = '").append(username).append("' ");
        }

        sb.append(" GROUP BY username ");

        // 计算数量
        sbCount.append(sb);

        if (isExcel != 1) {
            sb.append(" limit ").append((page - 1) * size).append(",").append(size);
        }
        List<HashMap<String, Object>> list = new ArrayList<>();
        List<HashMap<String, Object>> lists = new ArrayList<>();
        try {
            if (!isNoCount) {
                lists = (List<HashMap<String, Object>>) UserDaoSql.getInstance().queryBySql(sbCount.toString());
            }
            if (ValidateUtil.isAbsList(lists) || isNoCount) {
                list = (List<HashMap<String, Object>>) UserDaoSql.getInstance().queryBySql(sb.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("信息错误");
        }
        // 为空设置为0
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                if (null == list.get(i).get("wmCount")) {
                    list.get(i).put("wmCount", 0);
                }
                if (null == list.get(i).get("wmCost")) {
                    list.get(i).put("wmCost", 0);
                }
                if (null == list.get(i).get("ptCount")) {
                    list.get(i).put("ptCount", 0);
                }
                if (null == list.get(i).get("ptCost")) {
                    list.get(i).put("ptCost", 0);
                }
                if (null == list.get(i).get("squareCount")) {
                    list.get(i).put("squareCount", 0);
                }
                if (null == list.get(i).get("squareCost")) {
                    list.get(i).put("squareCost", 0);
                }

                String postmanUsername = null != list.get(i).get("username") ? list.get(i).get("username").toString() : "";
                if (ValidateUtil.isNotNull(postmanUsername)) {
                    // 获取配送员姓名
                    UserInfo info = UserInfoMemory.getInstance().getUserInfo(postmanUsername);
                    if (null != info) {
                        list.get(i).put("name", info.getName());
                    } else {
                        list.get(i).put("name", postmanUsername);
                    }
                } else {
                    list.get(i).put("name", "");
                }
            }
        }

        if (isExcel == null) {
            isExcel = 0;
        }
        if (isExcel == 1) {
            // 导出excel
            String downloadUrl = postmanOrderExcel(list);
            if (ValidateUtil.isNotNull(downloadUrl)) {
                if (ValidateUtil.isNotNetUrl(downloadUrl)) {
                    downloadUrl = SYS_CONFIG_PATH.IMAGE_BASE_URL + downloadUrl;
                }
                return AjaxResult.successResult(downloadUrl);
            }

        } else {
            if (ValidateUtil.isAbsList(list) && ValidateUtil.isAbsList(lists)) {
                return AjaxResult.successResult(list, lists.size());
            }
        }
        return AjaxResult.successResult(0, 0, null);

    }

    // 管理后台获取配送员的所有订单新
    @RequestMapping(method = RequestMethod.POST, value = "/admin/postman/order/list")
    @ResponseBody
    public String order_postman_over_list(String token, String postman, Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
        if (ValidateUtil.isNull(postman)) {
            return AjaxResult.successResult(null, 0);
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 15;
        }
        /**
         * SELECT  OI.orderNo,
         * 	OI.createTime,
         * 	OI.totalPrice,
         * 	OI.deliveryPrice,
         * 	OI.postmanFinishTime,
         * 	OI.orderType,
         * 	OI.shopName,
         * 	IFNULL(OP.postmanRate,0) AS postmanRate,
         * 	IFNULL(OP.postmanMoney,0) AS postmanMoney
         *
         *  FROM order_info OI
         *  LEFT JOIN order_pay OP ON OI.orderNo = OP.orderNo AND OP.delFlag = 0  WHERE OI.delFlag = 0 AND OI.postmanUsername = '13011742051' and AND OI.orderstatus = 9 AND OI.isRefundApply !=2;
         */
        StringBuffer sql = new StringBuffer();
        sql.append(" from ").append(PojoTables.OrderInfo).append(" OI LEFT JOIN ").append(PojoTables.OrderPay).append(" OP ON OI.orderNo = OP.orderNo and OP.delFlag = 0 ")
                .append(" where OI.delFlag = 0 and OI.isRefundApply !=").append(REFUND_APPLY_STATUS.PASS).append(" and OI.postmanUsername ='").append(postman).append("' and OI.orderStatus =").append(ORDER_STATUS.OVER);
        if (ValidateUtil.isAbsLong(startTime)) {
            sql.append(" and OI.createTime >").append(startTime);
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            sql.append(" and OI.createTime <").append(endTime);
        }
        String countSql = " select count(1) as counts " + sql.toString();
        String selectSql = " select " +
                " OI.orderNo," +
                " OI.username," +
                " OI.createTime," +
                " OI.totalPrice," +
                " OI.deliveryPrice," +
                " OI.postmanFinishTime," +
                " OI.orderType," +
                " OI.shopName," +
                " IFNULL(OP.postmanRate,0) AS postmanRate," +
                " IFNULL(OP.postmanMoney,0) AS postmanMoney " + sql.toString() + " limit " + (page - 1) * size + "," + size;
        Long count = 0L;
        List<HashMap<String, Object>> list = null;
        try {
            if (!isNoCount) {
                count = UserDaoSql.getInstance().getCount(countSql);
            }
            if (ValidateUtil.isAbsLong(count) || isNoCount) {
                list = UserDaoSql.getInstance().queryBySql(selectSql);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.successResult(null, 0);
        }
        return AjaxResult.successResult(list, count);
    }

    // 配送员外卖、跑腿订单统计
    @RequestMapping(method = RequestMethod.POST, value = "/postman/company/order/statistical/list")
    @ResponseBody
    public String order_postman_company_finish_list_v2(String token, String city, String county, String username, Integer postmanType, Integer isExcel, String cityAdminUsername, Long agentId,
                                                       Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 10;
        }
        if (isExcel == null) {
            isExcel = 0;
        }

        StringBuffer sb = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        sb.append("select m.username,m.type,IFNULL(t.wmCount,0) wmCount,IFNULL(t.wmCost,0) wmCost,IFNULL(f.ptCount,0) ptCount,IFNULL(f.ptCost,0) ptCost, ")
                .append(" IFNULL(p.isPost,0) isPost,IFNULL(c.isTrouble,0) isTrouble,IFNULL(commH.haoping,0) haoping,IFNULL(commC.chaping,0) chaping from ")
                .append(PojoTables.CityPostman).append(" m")
                .append(" left join ").append(PojoTables.POSTMAN_SIGN_COMPANY).append(" psc on psc.username=m.username and psc.delFlag=0 ")
                .append(" left join ").append(PojoTables.POST_COMPANY).append(" pc on pc.id=psc.companyId and pc.delFlag=0 ")
                .append(" left join ( select a.postmanUsername, a.grabCompanyId grabCompanyId, a.postmanName,count(a.orderNo) as wmCount, sum(b.postmanMoney) as wmCost from ")
                .append(PojoTables.OrderInfo).append(" a Left join ")
                .append(PojoTables.OrderPay).append(" b on a.orderno=b.orderno where a.orderType = ")
                .append(ORDER_TYPE.SHOP_GOODS).append("  and a.orderStatus = ")
                .append(ORDER_STATUS.OVER);
        // 外卖下单时间在开始时间和结束时间之间
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" and a.delFlag = 0 group by a.postmanUsername) t on t.postmanUsername = m.username and t.grabCompanyId=pc.id ");

        sb.append(" left join (select a.postmanUsername,a.grabCompanyId grabCompanyId, a.postmanName,count(a.orderNo) as ptCount,sum(b.postmanMoney) as ptCost from ")
                .append(PojoTables.OrderInfo).append(" a Left join ")
                .append(PojoTables.OrderPay).append(" b on a.orderno=b.orderno  where a.orderType = ")
                .append(ORDER_TYPE.PAO_TUI).append(" and a.orderStatus = ").append(ORDER_STATUS.OVER);
        // 跑腿下单时间在开始时间和结束时间之间
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" and a.delFlag = 0 group by a.postmanUsername) f  on m.username = f.postmanUsername and f.grabCompanyId=pc.id ");

        // 添加超时量统计字段
        sb.append(" LEFT JOIN (SELECT a.postmanUsername,a.grabCompanyId grabCompanyId, COUNT(1) AS isPost FROM ").append(PojoTables.OrderInfo)
//                .append(" a WHERE ((a.agentPostmanOverTime > 0 and ((a.postmanFinishTime - a.createTime) > (a.agentPostmanOverTime * 60 * 1000))) or (a.postmanFinishTime > a.ziQuTime))  AND")
                .append(" a WHERE ((a.agentPostmanOverTime > 0 and ((a.postmanFinishTime - a.createTime) > (a.agentPostmanOverTime * 60 * 1000))) or (a.ziQuTime>0 AND a.postmanFinishTime > a.ziQuTime))  AND")
                .append(" a.orderStatus = ").append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) p ON p.postmanUsername = m.username and p.grabCompanyId=pc.id ");

        // 添加异常上报统计字段
        sb.append(" LEFT JOIN (SELECT a.postmanUsername, a.grabCompanyId grabCompanyId, COUNT(1) AS isTrouble FROM ").append(PojoTables.OrderInfo).append(" a ")
                .append(" RIGHT JOIN ").append(PojoTables.ORDER_POSTMAN_TROUBLE)
                .append(" b ON a.orderNo=b.orderNo WHERE a.orderStatus =  ")
                .append(ORDER_STATUS.OVER).append(" AND a.delFlag = 0");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and b.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) c ON c.postmanUsername = m.username and c.grabCompanyId=pc.id ");

        // 好评数量
        sb.append(" LEFT JOIN (SELECT a.postmanUsername, a.grabCompanyId grabCompanyId, COUNT(1) AS haoping FROM ").append(PojoTables.OrderInfo)
                .append(" a LEFT JOIN ").append(PojoTables.ORDER_COMMENT).append(" b ON a.orderNO = b.orderNo ")
                .append(" LEFT JOIN ").append(PojoTables.ShopInfo).append(" si ON a.shopId = si.id ")
                .append(" WHERE a.orderStatus = ").append(ORDER_STATUS.OVER)
                .append(" AND a.delFlag = 0 AND b.delFlag = 0 and si.delFlag=0 and a.isRefundApply=0 and a.isPartCancelApply=0 AND b.star = 5 AND b.commentType = 2 ");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) commH ")
                .append(" ON commH.postmanUsername = m.username and commH.grabCompanyId=pc.id ");

        // 差评数量
        sb.append(" LEFT JOIN (SELECT a.postmanUsername, a.grabCompanyId grabCompanyId, COUNT(1) AS chaping FROM ").append(PojoTables.OrderInfo)
                .append(" a LEFT JOIN ").append(PojoTables.ORDER_COMMENT).append(" b ON a.orderNO = b.orderNo ")
                .append(" WHERE a.orderStatus = ").append(ORDER_STATUS.OVER)
                .append(" AND a.delFlag = 0 AND b.delFlag = 0 AND b.star = 1 AND b.commentType = 2 ");
        // 添加时间筛选
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime) && endTime > startTime) {
            sb.append(" and a.createTime between ").append(startTime).append(" and ").append(endTime);
        }
        sb.append(" GROUP BY a.postmanUsername) commC ")
                .append(" ON commC.postmanUsername = m.username and commC.grabCompanyId=pc.id ");

        sb.append(" LEFT JOIN ").append(PojoTables.POSTMAN_AGENT_RELATION).append(" par ON par.postmanUsername = m.username AND par.delFlag = 0 ");
        sb.append(" LEFT JOIN ").append(PojoTables.USER_AGENT_RELATION).append(" uar ON uar.agentId = par.agentId AND uar.delFlag = 0");
        sb.append(" where m.delFlag = 0 and pc.username=").append(user.getUsername()).append(" and psc.status=").append(PostmanSignCompanyInfo.POSTMAN_COMPANY_SIGN_STATUS_AGREE);
        if (null != postmanType && postmanType != 0) {
            sb.append(" and m.type=").append(postmanType).append(" ");
        }

        if (ValidateUtil.isNotNull(city)) {
            sb.append(" and m.city = '").append(city).append("'");
        }
        if (ValidateUtil.isNotNull(county)) {
            sb.append(" and m.county = '").append(county).append("'");
        }
        if (agentId != null) {
            sb.append(" and par.agentId = ").append(agentId);
        }
        if (ValidateUtil.isNotNull(cityAdminUsername)) {
            sb.append(" and uar.username = '").append(cityAdminUsername).append("' ");
        }

        if (ValidateUtil.isNotNull(username)) {
            sb.append(" and m.username = '").append(username).append("' ");
        }

        sb.append(" GROUP BY username ");

        // 计算数量
        sbCount.append(sb);

        if (isExcel != 1) {
            sb.append(" limit ").append((page - 1) * size).append(",").append(size);
        }
        List<HashMap<String, Object>> list = new ArrayList<>();
        List<HashMap<String, Object>> lists = new ArrayList<>();
        try {
            if (!isNoCount) {
                lists = (List<HashMap<String, Object>>) UserDaoSql.getInstance().queryBySql(sbCount.toString());
            }
            if (ValidateUtil.isAbsList(lists) || isNoCount) {
                list = (List<HashMap<String, Object>>) UserDaoSql.getInstance().queryBySql(sb.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("信息错误");
        }
        // 为空设置为0
        if (ValidateUtil.isAbsList(list)) {

            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                if (null == list.get(i).get("wmCount")) {
                    list.get(i).put("wmCount", 0);
                }
                if (null == list.get(i).get("wmCost")) {
                    list.get(i).put("wmCost", 0);
                }
                if (null == list.get(i).get("ptCount")) {
                    list.get(i).put("ptCount", 0);
                }
                if (null == list.get(i).get("ptCost")) {
                    list.get(i).put("ptCost", 0);
                }

                String postmanUsername = null != list.get(i).get("username") ? list.get(i).get("username").toString() : "";
                if (ValidateUtil.isNotNull(postmanUsername)) {
                    // 获取配送员姓名
                    UserInfo info = UserInfoMemory.getInstance().getUserInfo(postmanUsername);
                    if (null != info) {
                        list.get(i).put("name", info.getName());
                    } else {
                        list.get(i).put("name", postmanUsername);
                    }
                } else {
                    list.get(i).put("name", "");
                }
            }
        }

        if (isExcel == null) {
            isExcel = 0;
        }
        if (isExcel == 1) {
            // 导出excel
            String downloadUrl = postmanOrderExcel(list);
            if (ValidateUtil.isNotNull(downloadUrl)) {
                String url = SYS_CONFIG_PATH.IMAGE_BASE_URL + downloadUrl;
                return AjaxResult.successResult(url);
            }
        } else {
            if (ValidateUtil.isAbsList(list) && ValidateUtil.isAbsList(lists)) {
//                return AjaxResult.successResult(lists.size(), list.size(), list);
                return AjaxResult.successResult(list, lists.size());
            }
        }
        return AjaxResult.successResult(0, 0, null);

    }


    // 骑手获取退款订单列表(退款中和已退款订单)
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/refund/list")
    @ResponseBody
    public String order_postman_refund_list(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }

        //获取配送员所有已完成订单
        List<OrderInfo> list = PostmanOrderMemoryMan.listOfPostmanRefund(user.getUsername(), createTime, size);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }

                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }

                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, null);
    }


    //---------------------------------生成配送员订单统计Excel
    private String postmanOrderExcel(List<HashMap<String, Object>> list) {
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }
        String outputPath = "";
        try {
            outputPath = SYS_CONFIG_PATH.ORDER_IMAGE + "/" + DateUtils.getCurrentYearMonth() + "/" + DateUtils.getCurrTime() + ".xls";

            File outputFile = new File(SYS_CONFIG_PATH.IMAGE_BASE_FILE + outputPath);
            FileUtils.forceMkdirParent(outputFile);

            WritableWorkbook workbook = Workbook.createWorkbook(outputFile);
            // 生成名为"学生"的工作表，参数0表示这是第一页
            WritableSheet sheet = workbook.createSheet("sheet1", 0);
            jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#0.00");   // 设置数字格式
            jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf); // 设置表单格式
            int col = 0;   // 列
            int row = 0;  // 行
            sheet.addCell(new Label(col++, row, "配送员账号"));
            sheet.addCell(new Label(col++, row, "配送员姓名"));
            sheet.addCell(new Label(col++, row, "外卖单量"));
            sheet.addCell(new Label(col++, row, "跑腿单量"));
            if (Optional.ofNullable(SYS_SETTINGS.CUSTOM_SYSTEM_TYPE).orElse(0) == 1) {
                sheet.addCell(new Label(col++, row, "创业商圈单量"));
            }
            sheet.addCell(new Label(col++, row, "总单量"));
            sheet.addCell(new Label(col++, row, "外卖配送费"));
            sheet.addCell(new Label(col++, row, "跑腿配送费"));
            sheet.addCell(new Label(col++, row, "总配送费"));
            sheet.addCell(new Label(col++, row, "好评数量"));
            sheet.addCell(new Label(col++, row, "差评数量"));
            sheet.addCell(new Label(col++, row, "超时订单量"));
            sheet.addCell(new Label(col++, row, "异常上报数量"));
            row = 1;
            for (Map<String, Object> record : list) {
                col = 0;
                double totalPrice = 0;
                sheet.addCell(new Label(col++, row, record.get("username").toString()));
                sheet.addCell(new Label(col++, row, record.get("name").toString()));
                sheet.addCell(new Number(col++, row, Float.parseFloat(record.get("wmCount").toString())));
                sheet.addCell(new Label(col++, row, record.get("ptCount").toString()));
                if (Optional.ofNullable(SYS_SETTINGS.CUSTOM_SYSTEM_TYPE).orElse(0) == 1) {
                    sheet.addCell(new Label(col++, row, record.get("squareCount").toString()));
                }
                int wmCount = Integer.parseInt(record.get("wmCount").toString());
                int ptCount = Integer.parseInt(record.get("ptCount").toString());
                sheet.addCell(new Number(col++, row, wmCount + ptCount));
                sheet.addCell(new Label(col++, row, record.get("wmCost").toString()));
                sheet.addCell(new Label(col++, row, record.get("ptCost").toString()));
                Float wmCost = Float.parseFloat(record.get("wmCost").toString());
                Float ptCost = Float.parseFloat(record.get("ptCost").toString());
                sheet.addCell(new Number(col++, row, wmCost + ptCost));
                if (record.get("haoping").toString().equals("null")) {
                    String a = "1";
                }
                int haoping = record.get("haoping").toString().equals("null") ? 0 : Integer.parseInt(record.get("haoping").toString());
                int chaping = record.get("chaping").toString().equals("null") ? 0 : Integer.parseInt(record.get("chaping").toString());
                int isPost = record.get("isPost").toString().equals("null") ? 0 : Integer.parseInt(record.get("isPost").toString());
                int isTrouble = record.get("isTrouble").toString().equals("null") ? 0 : Integer.parseInt(record.get("isTrouble").toString());

                sheet.addCell(new Number(col++, row, haoping));
                sheet.addCell(new Number(col++, row, chaping));
                sheet.addCell(new Number(col++, row, isPost));
                sheet.addCell(new Number(col++, row, isTrouble));
                row++;     // 行
            }
            workbook.write();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            outputPath = JYFileUtils.saveFile2Oss(outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputPath;
    }

    // 超时订单量统计
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/statistical/outtime/list")
    @ResponseBody
    public String order_postman_outtime_list(String token, String postmanUsername,
                                             Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
//        if (startTime == null) {
//            startTime = DateUtils.getFirstDayOfMonth(new Date()).getTime();
//        }
//        if (endTime == null) {
//            endTime = new Date().getTime();
//        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 10;
        }
//        String sql = "select * from order_info";
//        String sql = "SELECT id,orderNo,shopName,postmanUsername,postmanSureTime,postmanFinishTime,postFailReason,postmanName,postmanPhone " +
//                "   FROM order_info WHERE isPostmanOverTime = 1 AND orderStatus = " + ORDER_STATUS.OVER + " AND delFlag = 0" +
//                (postmanUsername == null ? "" : (postmanUsername == "" ? "" : "  AND postmanUsername = " + postmanUsername)) +
//                "   AND createTime BETWEEN " + startTime + " AND " + endTime +
//                "   LIMIT " + ((page - 1) * size) + "," + size;


        StringBuffer sb = new StringBuffer();
        sb
                .append(" FROM order_info WHERE ((agentPostmanOverTime > 0 and ((postmanFinishTime - createTime) > (agentPostmanOverTime * 60 * 1000))) or (ziQuTime >0 and postmanFinishTime > ziQuTime)) AND orderStatus = " + ORDER_STATUS.OVER + " AND delFlag = 0  AND orderNo not like 'S%' ")
                .append(postmanUsername == null ? "" : (postmanUsername == "" ? "" : "  AND postmanUsername = " + postmanUsername));
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
            sb.append("   AND createTime BETWEEN " + startTime + " AND " + endTime);
        }

        StringBuffer selectSql = new StringBuffer();
        selectSql.append(" SELECT * ")
                .append(sb.toString())
                .append("   LIMIT " + ((page - 1) * size) + "," + size);

        StringBuffer countSql = new StringBuffer();
        countSql.append(" select count(1) as counts ")
                .append(sb.toString());
        Long count = 0L;
        List<HashMap<String, Object>> list = null;
        try {
            if (!isNoCount) {
                count = UserDaoSql.getInstance().getCount(countSql.toString());
            }
            if (ValidateUtil.isAbsLong(count) || isNoCount) {
                list = UserDaoSql.getInstance().queryBySql(selectSql.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        return AjaxResult.successResult(list, count);
        // JSONObject obj = new JSONObject();
        // obj.put("status", 1);
        // obj.put("data", JSONArray.toJSON(list == null ? Collections.emptyList() : list));
        // return obj.toString();
    }


    // 骑手异常上报统计
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/statistical/trouble/list")
    @ResponseBody
    public String order_postman_trouble_list(String token, String postmanUsername,
                                             Long startTime, Long endTime, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        boolean isNoCount = false;
        if (null != SYS_SETTINGS.SYS_SOS_MODEL) {
            switch (SYS_SETTINGS.SYS_SOS_MODEL) {
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_OVER_ALL:// 屏蔽已完成和全部订单
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_DB: {// 屏蔽数据库查询
                    return AjaxResult.successResult(null, 0);
                }
                case SYS_SOS_MODEL_TYPE.ADMIN_NO_TOTAL_COUNT: {// 屏蔽条数查询
                    isNoCount = true;
                }
                break;
            }
        }
//        if (startTime == null) {
//            startTime = DateUtils.getFirstDayOfMonth(new Date()).getTime();
//        }
//        if (endTime == null) {
//            endTime = new Date().getTime();
//        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 10;
        }
//        String sql = "select * from order_info";
//        String sql = " SELECT opt.id,opt.orderNo,opt.username,opt.province,opt.city,opt.county,opt.address,opt.lng,opt.lat,opt.troubleReason," +
//                " opt.createTime,ori.postmanName,ori.postmanPhone FROM order_postman_trouble opt " +
//                " LEFT JOIN order_info ori ON ori.orderNo=opt.orderNo " +
//                " WHERE opt.delFlag = 0 AND ori.delFlag = 0 " +
//                (postmanUsername == null ? "" : (postmanUsername == "" ? "" : "  AND opt.username = " + postmanUsername)) +
//                "   AND opt.createTime BETWEEN " + startTime + " AND " + endTime +
//                "   LIMIT " + ((page - 1) * size) + "," + size;


        StringBuffer sb = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        sb.append("SELECT opt.id,opt.orderNo,opt.username,opt.province,opt.city,opt.county,opt.address,opt.lng,opt.lat,opt.troubleReason,")
                .append(" opt.createTime,ori.postmanName,ori.postmanPhone FROM order_postman_trouble opt ")
                .append(" LEFT JOIN order_info ori ON ori.orderNo=opt.orderNo ")
                .append(" WHERE opt.delFlag = 0 AND ori.delFlag = 0 ")
                .append(postmanUsername == null ? "" : (postmanUsername == "" ? "" : "  AND opt.username = '" + postmanUsername)).append("' ");
        if (ValidateUtil.isAbsLong(startTime) && ValidateUtil.isAbsLong(endTime)) {
            sb.append(" AND opt.createTime BETWEEN " + startTime + " AND " + endTime);
        }
        sbCount.append(sb);
        sb.append("   LIMIT " + ((page - 1) * size) + "," + size);
        List<HashMap<String, Object>> list = null;
        Long totalCount = 0L;
        try {
            if (!isNoCount) {
                totalCount = UserDaoSql.getInstance().getCount(sbCount.toString());
            }
            if (ValidateUtil.isAbsLong(totalCount) || isNoCount) {
                list = UserDaoSql.getInstance().queryBySql(sb.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        JSONObject obj = new JSONObject();
        obj.put("status", 1);
        obj.put("totalCount", totalCount);
        obj.put("data", JSONArray.toJSON(list == null ? Collections.emptyList() : list));
        return obj.toString();
    }


    //----------------------------好管家

    /**
     * 工人骑手获取新订单(好管家)
     */
    @RequestMapping(method = RequestMethod.POST, value = "/postman/new/order/list")
    @ResponseBody
    public String getNewOrder(String token, Integer orderType, Long createTime, Integer page, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        // 根据配送类型获取不同的订单
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == cityPostman) {
            return AjaxResult.errorResult("请核实配送员信息");
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }
        if (!ValidateUtil.isAbsInteger(isLoadMore)) {
            isLoadMore = 0; // 默认不加载更多了
        }

        // 工人只获取维修和救援订单
        if (cityPostman.getType() != null && cityPostman.getType() == POSTMAN_TYPE.WORKER) {
            //骑手所属商圈
            Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(user.getUsername());
            List<OrderInfo> lists = PostmanOrderMemoryMan2.listOfReGrabRepairOrderList(agentId, user.getUsername(), orderType);
            //分页
            Boolean flag = false;//需不需要判断时间戳
            if (null != createTime && createTime > 0) {
                flag = true;
            }
            if (null == size) {
                size = 20;
            }
            if (ValidateUtil.isAbsList(lists)) {
                List<OrderInfoVO> orderInfoList = new ArrayList<>();
                for (int i = 0; i < lists.size(); i++) {
                    OrderInfo orderInfo = lists.get(i);
                    if (null == orderInfo) {//存在
                        continue;
                    }

                    if (flag) {//需要判断时间戳
                        if (0 == 1 - isLoadMore) {//是否为加载更多  1加载更多，0非加载更多
                            if (orderInfo.getCreateTime() < createTime) {
                                OrderInfoVO infoVO = convertOneToVO(orderInfo);
                                if (null == infoVO) {
                                    continue;
                                }
                                orderInfoList.add(infoVO);
                            }
                        } else {
                            if (orderInfo.getCreateTime() > createTime) {
                                OrderInfoVO infoVO = convertOneToVO(orderInfo);
                                if (null == infoVO) {
                                    continue;
                                }
                                orderInfoList.add(infoVO);
                            }
                        }

                    } else {
                        OrderInfoVO infoVO = convertOneToVO(orderInfo);
                        if (null == infoVO) {
                            continue;
                        }
                        orderInfoList.add(infoVO);
                    }
                }
                if (ValidateUtil.isAbsList(orderInfoList)) {
                    //排序订单，返回前size条
                    JYListSort.sortDesc(orderInfoList, "createTime");
                    List<OrderInfoVO> reList = new ArrayList<>();
                    for (int i = 0; i < orderInfoList.size(); i++) {
                        if (i < size) {
                            reList.add(orderInfoList.get(i));
                        }
                    }

                    if (ValidateUtil.isAbsList(reList)) {
                        return AjaxResult.successResult(reList.size(), reList);
                    }
                }
            }

        } else {
            // 购物 租赁 跑腿
            //获取该城市订单
            List<OrderInfo> orderList = null;
            if (ValidateUtil.isAbsInteger(SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT)) {
                if (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.CITY - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) {//按城市获取
                    orderList = CityOrderMemoryMan.cityUnDeliveryList(cityPostman.getCity(), cityPostman.getCounty(), cityPostman.getRegion(), createTime, isLoadMore, orderType, cityPostman.getType(), null, false, null);
                } else if (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) {//按代理获取
//                    Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(user.getUsername());
                    List<Long> postmanAgentList = PostmanAgentRelationMemory.getInstance().listOfAgentIdByPostman(user.getUsername());
                    orderList = AgentOrderMemoryMan.agentUnDeliveryList(postmanAgentList, createTime, isLoadMore, orderType, cityPostman.getType(), cityPostman.getUsername(), null, false);

//                    orderList = AgentOrderMemoryMan.agentUnDeliveryList(agentId, createTime, size, isLoadMore, orderType, cityPostman.getType());
//                    orderList = AgentOrderMemoryMan.agentUnDeliveryList(agentId, createTime, size, isLoadMore, orderType, cityPostman.getType(), null);
                }
            } else {//默认按城市
                orderList = CityOrderMemoryMan.cityUnDeliveryList(cityPostman.getCity(), cityPostman.getCounty(), cityPostman.getRegion(), createTime, isLoadMore, orderType, cityPostman.getType(), null, false, null);
            }


            if (ValidateUtil.isAbsList(orderList)) {
//                List<OrderInfoVO> orderInfoVOList = new ArrayList<OrderInfoVO>();
//                for (int i = 0; i < orderList.size(); i++) {
//                    if (null == orderList.get(i)) {
//                        continue;
//                    }
//
//                    OrderInfoVO orderInfoVO = new OrderInfoVO();
//                    try {
//                        ObjectUtils.copyPropertiesExclude(orderList.get(i), orderInfoVO, null);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        continue;
//                    }
//                    if (null == orderInfoVO) {
//                        continue;
//                    }
//                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
////                        orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
//                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
//                    }
//
//                    if (null != orderInfoVO.getOrderType() && 0 == ORDER_TYPE.SERVICE_LOCK - orderInfoVO.getOrderType()) {
//                        List<OrderGoodsLabelVO> labels = OrderListMan.listOfOrderNO(orderInfoVO.getOrderNo());
//                        orderInfoVO.setLabelList(labels);
//                    }
//
//                    orderInfoVOList.add(orderInfoVO);
//                }
                // 分页判断
                long totalCount = 0;
                List<OrderInfo> newList = null;
                if (ValidateUtil.isNotAbsInteger(page)) {
//                    newList = orderList.subList(0, size - 1);
                    if (orderList.size() > size) {
                        newList = orderList.subList(0, size - 1);
                    } else {
                        newList = orderList;
                    }
                } else {
                    // 分页
                    JYPageUtils.PageList pageList = JYPageUtils.getList(orderList, page, size);
                    newList = (List<OrderInfo>) pageList.list;
                    totalCount = pageList.totalCount;
                }

                List<OrderInfoVO> orderInfoVOList = convertToVO(newList);
                if (ValidateUtil.isAbsList(orderInfoVOList)) {
                    return AjaxResult.successResult(orderInfoVOList, totalCount);
                }
            }
        }
        return AjaxResult.successResult(0, null);
    }

    private List<OrderInfoVO> convertToVO(List<OrderInfo> list) {
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> infoVOList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                //拷贝订单
                OrderInfoVO infoVO = convertOneToVO(list.get(i));
                if (null == infoVO) {
                    continue;
                }

                infoVOList.add(infoVO);
            }
            return infoVOList;
        }

        return null;
    }

    private OrderInfoVO convertOneToVO(OrderInfo info) {
        if (null == info) {
            return null;
        }
        //拷贝订单
        OrderInfoVO infoVO = new OrderInfoVO();
        try {
            ObjectUtils.copyPropertiesExclude(info, infoVO);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if (ValidateUtil.isNotNull(infoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(infoVO.getShopImageUrl())) {
            infoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + infoVO.getShopImageUrl());
        }

        if (null != infoVO.getOrderType() && (0 == ORDER_TYPE.SHOP_SERVICE - infoVO.getOrderType() || 0 == ORDER_TYPE.SHOP_RESCUE - infoVO.getOrderType())) {
            List<OrderGoodsLabelVO> labels = OrderListMan.listOfOrderNO(infoVO.getOrderNo());
            infoVO.setLabelList(labels);

            //获取相关图片
            List<OrderInfoImage> imageList = OrderInfoImageMemory.getInstance().listOfOrderNo(info.getOrderNo());
            if (ValidateUtil.isAbsList(imageList)) {
                List<OrderInfoImageVO> imageVOList = new ArrayList<>();
                //遍历
                for (int j = 0; j < imageList.size(); j++) {
                    if (null == imageList.get(j)) {
                        continue;
                    }
                    //拷贝图片
                    OrderInfoImageVO imageVO = new OrderInfoImageVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(imageList.get(j), imageVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    imageVOList.add(imageVO);
                }
                //设置图片信息
                infoVO.setImageList(imageVOList);
            }

        }

        return infoVO;
    }


    // 工人骑手获取进行中订单(好管家)
    @RequestMapping(method = RequestMethod.POST, value = "/postman/ing/order/list")
    @ResponseBody
    public String getIngOrder(String token, Integer orderType, Long createTime, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //获取订单
        List<OrderInfo> lists = PostmanOrderMemoryMan2.listOfIngOrder(user.getUsername(), orderType, createTime, size, isLoadMore);
        //订单设置
        List<OrderInfoVO> infoVOList = new ArrayList<>();
        OrderInfoVO infoVO = null;
        if (null != lists && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (null == lists.get(i)) {
                    continue;
                }
                //拷贝订单
                infoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(lists.get(i), infoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                //获取相关图片
                List<OrderInfoImage> imageList = OrderInfoImageMemory.getInstance().listOfOrderNo(lists.get(i).getOrderNo());
                List<OrderInfoImageVO> imageVOList = new ArrayList<>();
                //遍历
                if (null != imageList && imageList.size() > 0) {
                    for (int j = 0; j < imageList.size(); j++) {
                        if (null == lists.get(j)) {
                            continue;
                        }
                        //拷贝图片
                        OrderInfoImageVO imageVO = new OrderInfoImageVO();
                        try {
                            ObjectUtils.copyPropertiesExclude(imageList.get(j), imageVO, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        }
                        imageVOList.add(imageVO);
                    }
                    //设置图片信息
                    infoVO.setImageList(imageVOList);
                }
                infoVOList.add(infoVO);
            }
        }
        if (ValidateUtil.isAbsList(infoVOList)) {
            return AjaxResult.successResult(infoVOList.size(), infoVOList);
        }
        return AjaxResult.successResult(0, null);
    }

    // 工人骑手获取已完成订单(好管家)
    @RequestMapping(method = RequestMethod.POST, value = "/postman/finish/order/list")
    @ResponseBody
    public String getFinishOrder(String token, Integer orderType, Long createTime, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }
        if (!ValidateUtil.isAbsInteger(isLoadMore)) {
            isLoadMore = 0; // 默认不加载更多了；
        }
//        if(!ValidateUtil.isAbsLong(createTime)){
//            createTime = 0L;
//        }

        //获取订单
        List<OrderInfo> lists = PostmanOrderMemoryMan2.listOfFinishOrder(user.getUsername(), orderType, createTime, size, isLoadMore);
        //订单设置
        List<OrderInfoVO> infoVOList = new ArrayList<>();
        OrderInfoVO infoVO = null;
        if (null != lists && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (null == lists.get(i)) {
                    continue;
                }
                //拷贝订单
                infoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(lists.get(i), infoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                //获取相关图片
                List<OrderInfoImage> imageList = OrderInfoImageMemory.getInstance().listOfOrderNo(lists.get(i).getOrderNo());
                List<OrderInfoImageVO> imageVOList = new ArrayList<>();
                //遍历
                if (null != imageList && imageList.size() > 0) {
                    for (int j = 0; j < imageList.size(); j++) {
                        if (null == lists.get(j)) {
                            continue;
                        }
                        //拷贝图片
                        OrderInfoImageVO imageVO = new OrderInfoImageVO();
                        try {
                            ObjectUtils.copyPropertiesExclude(imageList.get(j), imageVO, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        }
                        imageVOList.add(imageVO);
                    }
                    //设置图片信息
                    infoVO.setImageList(imageVOList);
                }
                infoVOList.add(infoVO);
            }
        }
        if (ValidateUtil.isAbsList(infoVOList)) {
            return AjaxResult.successResult(infoVOList.size(), infoVOList);
        }
        return AjaxResult.successResult(0, null);
    }

    //--------------------------美羹

    /**
     * 获取待领取订单(商家已发货、配送员确认领货)
     */
    @RequestMapping(method = RequestMethod.POST, value = "/postman/order/need/pull/list")
    @ResponseBody
    public String order_postman_station_list(String token, Long createTime, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        //是否为加载更多，0不是，1是
        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 1;
        }

        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }

        //判断是否为提货点
        if (0 != POSTMAN_TYPE.STATION - postman.getType()) {
            return AjaxResult.errorResult("您不是提货点，请使用提货点账号登录");
        }

        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法接单");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }

        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            // 必须缴纳
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }

            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(user.getUsername());
        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("您的信息不完整，请联系客服");
        }
        //获取配送员所有已完成订单
        List<OrderInfo> list = PostmanOrderMemoryMan2.listOfPostmanNeedPull(agentId, createTime, size, isLoadMore);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVerifyVO> voList = new ArrayList<OrderInfoVerifyVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVerifyVO orderInfoVO = new OrderInfoVerifyVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }

                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }


        return AjaxResult.successResult(0, null);
    }

    // -------------------------------二级配送员相关操作

    /**
     * 二级配送员获取最新订单
     */
    @RequestMapping(method = RequestMethod.POST, value = "/secondary/postman/order/new/list")
    @ResponseBody
    public String order_secondary_postman_new_list(String token, Integer orderType, Long createTime, Integer page, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        CityPostman postman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == postman) {
            return AjaxResult.errorResult("未查询到您的信息，无法操作");
        }
        //0 锁定  1未锁定
        if (null != postman.getIsLock() && 0 == 1 - postman.getIsLock()) {
            return AjaxResult.errorResult("您已被锁定，无法接单");
        }
        if (ValidateUtil.isNotAbsInteger(postman.getIsWork())) {
            return AjaxResult.errorResult("您无法接单，请先上班");
        }
        if (0 == postman.getIsWork()) {
            return AjaxResult.errorResult("请先上班");
        }
        // 众包端骑手类型检测
        if (postman.getType() == null || postman.getType() != POSTMAN_TYPE.POSTMAN_2) {
            return AjaxResult.errorResult("您不是众包端骑手");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                && (null == postman.getIsVerify() || 0 != 1 - postman.getIsVerify())) {
            return AjaxResult.errorResult("您尚未通过认证，请先去认证");
        }
        if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
            if (null != user.getIsCert() && 0 == 1 - user.getIsCert()) {
                //已认证
            } else {
                return AjaxResult.errorResult("未通过实名认证，请先去认证");
            }
        }

        // 必须缴纳？
        if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
            //验证押金金额是否满足
            UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
            if (null == userWallet) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金");
            }
            if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                return AjaxResult.errorResult("您还未缴纳押金，请先缴纳押金！");
            }
            //必须缴纳的押金金额
            Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
            if (null == money) {
                money = 0d;
            }
            if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                return AjaxResult.errorResult("您缴纳的押金不足，请先缴纳押金");
            }
        }

        //是否为加载更多，0不是，1是
        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 0;
        }

        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        //无最新指定订单，返回待抢订单
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null != cityPostman) {
            //获取该城市订单
            List<OrderInfo> orderList = null;
            if (ValidateUtil.isAbsInteger(SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT)) {
                if (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.CITY - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) {//按城市获取
                    orderList = CityOrderMemoryMan.cityUnSecondaryDeliveryList(cityPostman.getCity(), createTime, isLoadMore, orderType, cityPostman.getType(), cityPostman.getUsername());
                } else if (0 == POSTMAN_IN_CITY_OR_AGENT_DATA.AGENT - SYS_SETTINGS.POSTMAN_IN_CITY_OR_AGENT) { //按代理获取
                    // 一个骑手可以服务多个商圈
                    List<Long> postmanAgentList = PostmanAgentRelationMemory.getInstance().listOfAgentIdByPostman(user.getUsername());
                    orderList = AgentOrderMemoryMan.agentUnSecondaryDeliveryList(postmanAgentList, createTime, isLoadMore, orderType, cityPostman.getType(), cityPostman.getUsername());
                }
            } else {//默认按城市
                orderList = CityOrderMemoryMan.cityUnSecondaryDeliveryList(cityPostman.getCity(), createTime, isLoadMore, orderType, cityPostman.getType(), cityPostman.getUsername());
            }
            if (ValidateUtil.isAbsList(orderList)) {
                // 分页判断
                long totalCount = 0;
                List<OrderInfo> newList = null;
                if (ValidateUtil.isNotAbsInteger(page)) {
//                    newList = orderList.subList(0, size - 1);
                    if (orderList.size() > size) {
                        newList = orderList.subList(0, size - 1);
                    } else {
                        newList = orderList;
                    }
                } else {
                    // 分页
                    JYPageUtils.PageList pageList = JYPageUtils.getList(orderList, page, size);
                    newList = (List<OrderInfo>) pageList.list;
                    totalCount = pageList.totalCount;
                }
                List<OrderInfoVO> orderInfoVOList = new ArrayList<OrderInfoVO>();
                for (int i = 0; i < newList.size(); i++) {
                    if (null == newList.get(i)) {
                        continue;
                    }
                    OrderInfoVO orderInfoVO = new OrderInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(newList.get(i), orderInfoVO, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    if (null == orderInfoVO) {
                        continue;
                    }
                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    // 店铺
                    if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                        orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                    }
                    // 一级骑手
                    if (ValidateUtil.isNotNull(orderInfoVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getPostmanImageUrl())) {
                        orderInfoVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getPostmanImageUrl());
                    }
                    // 二级骑手
                    if (ValidateUtil.isNotNull(orderInfoVO.getSecondaryPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getSecondaryPostmanImageUrl())) {
                        orderInfoVO.setSecondaryPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getSecondaryPostmanImageUrl());
                    }
                    orderInfoVOList.add(orderInfoVO);
                }
                return AjaxResult.successResult(orderInfoVOList, totalCount);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    //   二级配送员已抢订单
    @RequestMapping(method = RequestMethod.POST, value = "/secondary/postman/order/grab/list")
    @ResponseBody
    public String order_secondary_postman_new_grab_list(String token, Long createTime, String username, Integer size, Integer isLoadMore) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //如果createTime是-1  是获取所有进行中订单
        if (null == createTime) {
            createTime = 0l;
        }

        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        //是否为加载更多，0不是，1是
        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 1;
        }
        if (ValidateUtil.isNull(username)) {
            username = user.getUsername();
        }
        //获取配送员所有已完成订单
        List<OrderInfo> list = PostmanOrderMemoryMan2.listOfSecondaryPostmanGrab(username, createTime, size, isLoadMore);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVerifyVO> voList = new ArrayList<OrderInfoVerifyVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVerifyVO orderInfoVO = new OrderInfoVerifyVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                // 店铺
                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                // 一级骑手
                if (ValidateUtil.isNotNull(orderInfoVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getPostmanImageUrl())) {
                    orderInfoVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getPostmanImageUrl());
                }
                // 二级骑手
                if (ValidateUtil.isNotNull(orderInfoVO.getSecondaryPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getSecondaryPostmanImageUrl())) {
                    orderInfoVO.setSecondaryPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getSecondaryPostmanImageUrl());
                }
                voList.add(orderInfoVO);
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    // 二级已抢待取货或者配送中的订单接口
    @RequestMapping(method = RequestMethod.POST, value = "/secondary/postman/order/wait-post/list")
    @ResponseBody
    public String secondary_order_postman_new_grab_wait_list(String token, Long createTime, String username, Integer size, Integer isLoadMore, Integer posting) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //如果createTime是-1  是获取所有进行中订单
        if (null == createTime) {
            createTime = 0l;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }
        //是否为加载更多，0不是，1是
        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 1;
        }
        if (ValidateUtil.isNull(username)) {
            username = user.getUsername();
        }
        boolean isWait = true;
        if (posting != null && posting == 1) {
            isWait = false;
        }
        List<OrderInfo> list = PostmanOrderMemoryMan2.listOfSecondaryPostmanWaitOrPost(username, createTime, size, isLoadMore, isWait);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVerifyVO> voList = new ArrayList<OrderInfoVerifyVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVerifyVO orderInfoVO = new OrderInfoVerifyVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }
                // 店铺
                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                // 一级骑手
                if (ValidateUtil.isNotNull(orderInfoVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getPostmanImageUrl())) {
                    orderInfoVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getPostmanImageUrl());
                }
                // 二级骑手
                if (ValidateUtil.isNotNull(orderInfoVO.getSecondaryPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getSecondaryPostmanImageUrl())) {
                    orderInfoVO.setSecondaryPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getSecondaryPostmanImageUrl());
                }
                voList.add(orderInfoVO);
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    // 二级骑手已完成订单
    @RequestMapping(method = RequestMethod.POST, value = "/secondary/postman/order/finish/list")
    @ResponseBody
    public String order_secondary_postman_finish_list(String token, Long createTime, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotAbsLong(createTime)) {
            createTime = 0l;
        }
        if (!ValidateUtil.isAbsInteger(size)) {
            size = 20;
        }

        //获取配送员所有已完成订单
        List<OrderInfo> list = PostmanOrderMemoryMan2.listOfSecondaryDeliveryFinish(user.getUsername(), createTime, size);
        if (ValidateUtil.isAbsList(list)) {
            List<OrderInfoVO> voList = new ArrayList<OrderInfoVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderInfoVO orderInfoVO = new OrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null == orderInfoVO) {
                    continue;
                }

                if (ValidateUtil.isNotNull(orderInfoVO.getShopImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getShopImageUrl())) {
//                    orderInfoVO.setShopImageUrl(Common.imageUrl + orderInfoVO.getShopImageUrl());
                    orderInfoVO.setShopImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getShopImageUrl());
                }
                // 一级骑手
                if (ValidateUtil.isNotNull(orderInfoVO.getPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getPostmanImageUrl())) {
                    orderInfoVO.setPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getPostmanImageUrl());
                }
                // 二级骑手
                if (ValidateUtil.isNotNull(orderInfoVO.getSecondaryPostmanImageUrl()) && ValidateUtil.isNotNetUrl(orderInfoVO.getSecondaryPostmanImageUrl())) {
                    orderInfoVO.setSecondaryPostmanImageUrl(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderInfoVO.getSecondaryPostmanImageUrl());
                }
                voList.add(orderInfoVO);
            }

            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    //一级骑手订单数量
    // 待取货  待配送 已完成订单列表
    @RequestMapping("/postman/order/state/count")
    @ResponseBody
    public String order_list_count(String token, String orderTypes) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.successResult();
        }
        Set<Integer> orderSet = null;
        if (ValidateUtil.isNotNull(orderTypes)) {
            orderSet = CommonUtils.splitToSet(orderTypes, Integer.class);
        }
        Map<String, Integer> map = UserOrderMan.getPostmanOrderCountByType(user.getUsername(), orderSet);
        return AjaxResult.successResult(map);
    }

    //获取当前订单的顺路单数量
    @ApiOperation("获取当前订单的顺路单数量")
    @PostMapping("/postman/order/on/the/way/count")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "用户登录凭证",required = true),
            @ApiImplicitParam(name = "orderNo",value = "订单编号",required = true),
            @ApiImplicitParam(name = "lat",value = "骑手纬度",required = true),
            @ApiImplicitParam(name = "lng",value = "骑手经度",required = true),
            @ApiImplicitParam(name = "createTime",value = "创建时间"),
            @ApiImplicitParam(name = "username",value = "骑手名称"),
            @ApiImplicitParam(name = "size",value = "显示的最大条数"),
            @ApiImplicitParam(name = "isLoadMore",value = "是否加载更多"),
    })
    public String order_on_the_way_count(String token,String orderNo,Double lat,Double lng,Long createTime, String username, Integer size, Integer isLoadMore){
        //验证用户的有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user==null){
            return AjaxResult.errorLogoutResult();
        }

        if (createTime==null){
            createTime = 0L;
        }

        if (ValidateUtil.isNotAbsInteger(size)){
            size = 20;
        }

        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 1;
        }

        if (ValidateUtil.isNull(username)) {
            username = user.getUsername();
        }

        //获取当前的订单
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (orderInfo == null){
            return AjaxResult.errorResult("订单不存在，请检查订单");
        }

        int count = 0;

        //获取配送员已抢的订单
        List<OrderInfo> list = PostmanOrderMemoryMan.listOfPostmanGrab(username, createTime, size, isLoadMore);
        if (!ValidateUtil.isAbsList(list)){
            return AjaxResult.successResult(String.valueOf(count));
        }
        for (OrderInfo info : list) {
            boolean flag = whetherToDropBy(orderInfo,lat,lng,info);
            if (flag){
                count++;
            }
        }
        return AjaxResult.successResult(String.valueOf(count));
    }

    /**
     * 判断当前订单是否顺路
     * @param orderInfo 当前订单
     * @param lat 骑手的纬度
     * @param lng 骑手的经度
     * @param info 骑手已抢订单
     * @return 是否顺路
     */
    private boolean whetherToDropBy(OrderInfo orderInfo, Double lat, Double lng, OrderInfo info) {
        boolean flag = false;
        //新订单取货距离
        double d1 = Geohash.distance(orderInfo.getShopLat(), orderInfo.getShopLng(), lat, lng);
        //新订单送货距离
        double d2 = Geohash.distance(orderInfo.getLat(), orderInfo.getLng(), lat, lng);
        //待取货
        if (info.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE
                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_ZD_SURE_BEFORE_SHOP
                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_DAODIAN
                || info.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_SUER
                || info.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_DAODIAN
                || info.getOrderStatus() == ORDER_STATUS.SHOP_READY
                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_SURE_BEFORE_SHOP){
            //新订单要与要与待取货订单夹角
            double angle = AngleUtils.getSubAngle(lat, lng, info.getShopLat(), info.getShopLng(), orderInfo.getShopLat(), orderInfo.getShopLng());
            //骑手距离新订单取货要比送货近并且距离小于3公里
            //新订单要与要与待取货订单夹角小于15度
            if (d1<3000 && d2<3000 && d1<d2 && angle<15){
                flag = true;
            }
        }
        //配送中
        if (info.getOrderStatus() == ORDER_STATUS.POSTMAN_PULL_GOODS
                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_ARRIVED
                || info.getOrderStatus() == ORDER_STATUS.SHOP_PUSH_GOODS
                || info.getOrderStatus() == ORDER_STATUS.POSTMAN_RECEIVING_PASSENGER
                || info.getOrderStatus() == ORDER_STATUS.SECONDARY_POSTMAN_SURE_AFTER_P_PULL
                || info.getOrderStatus() == ORDER_STATUS.PEISONG){
            //新订单要与要与配送中订单夹角小于15度
            double angle = AngleUtils.getSubAngle(lat, lng, info.getLat(), info.getLng(), orderInfo.getShopLat(), orderInfo.getShopLng());
            if (d1<3000 && d2<3000 && d1<d2 && angle<15){
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 获取配送员信息
     *
     * @param
     * @return
     */
    @RequestMapping("/postman/order/getPostmanList")
    @ResponseBody
    public IPage<Map<String, Object>> getPostmanList(@RequestBody CityPostmanVO cityPostmanVO) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(cityPostmanVO.getCurrent(), cityPostmanVO.getSize());
        IPage<Map<String, Object>> postmanList = cityPostmanMapper.getPostmanList(page, cityPostmanVO);
        return postmanList;
    }


    /**
     * 获取订单信息
     *
     * @param
     * @return
     */
    @RequestMapping("/postman/order/getOrderList")
    @ResponseBody
    public IPage<Map<String, Object>> getOrderList(@RequestBody OrderInfoVO orderInfoVO) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(orderInfoVO.getCurrent(), orderInfoVO.getSize());
        Set<Integer> setInteger = new HashSet<Integer>();
        switch (orderInfoVO.getOrderStatus()){
            // 待确定(提交订单)
            case -1:{
                setInteger.add(ORDER_STATUS.SUBMIT);
                setInteger.add(ORDER_STATUS.PAYED);
                orderInfoVO.setOrderSetStatus(setInteger);
                break;
            }
            // 待取货
            case -2:{
                setInteger = new HashSet<>( ORDER_STATUS.userWaitForPickSet);
                // 去除状态2时骑手未有骑手接单的订单
                setInteger.remove(ORDER_STATUS.PAYED);
                orderInfoVO.setOrderSetStatus(setInteger);
                break;
            }
            // 配送中
            case -3:{
                setInteger.add(ORDER_STATUS.POSTMAN_PULL_GOODS);
                orderInfoVO.setOrderSetStatus(setInteger);
                break;
            }
            // 已送达
            case -4:{
                setInteger.add(ORDER_STATUS.POSTMAN_FINISH);
                orderInfoVO.setOrderSetStatus(setInteger);
                break;
            }
            // 已取消
            case -5:{
                orderInfoVO.setOrderSetStatus(ORDER_STATUS.userOrderCancelSet);
                break;
            }
            // 已完成
            case -6:{
                setInteger.add(ORDER_STATUS.OVER);
                orderInfoVO.setOrderSetStatus(setInteger);
                break;
            }
            default:break;
        }
        IPage<Map<String, Object>> postmanList = cityPostmanMapper.getOrderList(page, orderInfoVO);
        return postmanList;
    }

    /**
     * 获取调度台初始化数据
     *
     * @return
     */
    @RequestMapping("/postman/order/getDispatcherStation")
    @ResponseBody
    public Map<String, Object> getDispatcherStation(@RequestBody(required = false) OrderInfoVO orderInfoVO) {
        Map<String, Object> map = new HashMap();
        List<Map<String, Object>> stationCountMap = cityPostmanMapper.getDispatcherStationCount(orderInfoVO);
        List<Map<String, Object>> stationHoneycombMap = cityPostmanMapper.getDispatcherStationHoneycomb();
        map.put("stationCountMap", stationCountMap);
        map.put("stationHoneycombMap", stationHoneycombMap);
        return map;
    }

    /**
     * 统计骑手订单完成与未完成数量
     *
     * @param postmanVO
     * @return
     */
    @RequestMapping("/postman/order/getDispatcherSelect")
    @ResponseBody
    public List<Map<String, Object>> getDispatcherSelect(@RequestBody CityPostmanVO postmanVO) {
        List<Map<String, Object>> stationCountStatusMap = cityPostmanMapper.getDispatcherStationCountStatus(postmanVO);
        return stationCountStatusMap;
    }

    /**
     * 通过订单号获取其下蜂窝里骑手及驻店骑手
     *
     * @param orderNo
     * @return
     */
    @RequestMapping("/postman/order/getOrderIsPosition")
    @ResponseBody
    public Map<String,Object> getOrderIsPosition(@RequestParam(value = "orderNo") String[] orderNo,
                                                 @RequestParam(value = "isWork", required = false) Integer isWork,
                                                 @RequestParam(value = "postmanType", required = false) Integer postmanType,
                                                 @RequestParam(value = "orderCount", required = false) Integer orderCount) {
        Map<String,Object> map = new HashMap<>();
        List<Map<String, Object>> orderIsPositionMap = cityPostmanMapper.getOrderIsPosition(orderNo,isWork,postmanType);
        OrderInfo orderInfo = cityPostmanMapper.getPostmanInfo(orderNo[0]);
        map.put("orderInfo",orderInfo);

        if (orderCount != null) {
            // 过滤订单过满骑手的数据
            if (orderCount == 0) {
                orderIsPositionMap = orderIsPositionMap.stream().
                        filter((e) -> e.get("userName") != null &&
                                orderCount.equals(PostmanOrderMemoryMan.getPostmanIngOrderCount(e.get("userName") + ""))).collect(Collectors.toList());

            } else if (orderCount == 3 || orderCount == 5) {
                orderIsPositionMap = orderIsPositionMap.stream().
                        filter((e) -> e.get("userName") != null &&
                                PostmanOrderMemoryMan.getPostmanIngOrderCount(e.get("userName") + "") < orderCount).collect(Collectors.toList());
            }
        }
        map.put("postman",orderIsPositionMap);
        return map;
    }

    /**
     * 批量设置工作状态
     * @param userName
     * @param isWork
     * @return
     */
    @RequestMapping("/postman/order/setIsWork")
    @ResponseBody
    public String setIsWork(@RequestParam("userName") String[] userName,
                            @RequestParam("isWork") Integer isWork){
        int i = cityPostmanMapper.updatePostmanIsWork(userName,isWork);

        // TODO 刷新该骑手的缓存
        Arrays.stream(userName).forEach(e->{
            CityPostmanMemory.getInstance().setIsWork(e,isWork);
        });
        if(i == 0){
            return AjaxResult.errorResult("设置失败，请重试");
        }
        return AjaxResult.successResult("设置成功！");
    }


    /**
     * 统计骑手取餐、送餐和超时的订单量
     * @param userName
     * @return
     */
    @RequestMapping("/postman/order/getPostmanDeliveryCount")
    @ResponseBody
    public int[] getPostmanDeliveryCount(@RequestParam("userName")String userName){
        //已超时
        int overTimeCount = cityPostmanMapper.queryOverTimeCount(userName);
        // 待取货和送货中
        Map<String, BigDecimal> map = cityPostmanMapper.countOrderPickAndPostByPostman(userName);
        int[] ints = new int[]{map.get("pick").intValue(),map.get("post").intValue(),overTimeCount};
        return ints;
    }

    //忽略token获取当前订单的顺路单数量
    @PostMapping("/postman/order/on/the/way/new/count")
    @ResponseBody
    public String order_on_the_way_count(String orderNo,Double lat,Double lng,Long createTime, String username, Integer size, Integer isLoadMore){
        //验证用户的有效性
        UserInfo user = UserInfoMemory.getInstance().getSuperAdmin();

        if(lat==null || lng==null){
            return AjaxResult.errorResult("订单收货地址坐标获取异常");
        }

        if (createTime==null){
            createTime = 0L;
        }

        if (ValidateUtil.isNotAbsInteger(isLoadMore)) {
            isLoadMore = 1;
        }

        if (ValidateUtil.isNull(username)) {
            username = user.getUsername();
        }
        size = 10000;
        //获取当前的订单
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (orderInfo == null){
            return AjaxResult.errorResult("订单不存在，请检查订单");
        }

        int count = 0;

        //获取配送员已抢的订单
        List<OrderInfo> list = PostmanOrderMemoryMan.listOfPostmanGrab(username, createTime, size, isLoadMore);
        if (!ValidateUtil.isAbsList(list)){
            return AjaxResult.successResult(String.valueOf(count));
        }
        for (OrderInfo info : list) {
            boolean flag = whetherToDropBy(orderInfo,lat,lng,info);
            if (flag){
                count++;
            }
        }
        return AjaxResult.successResult(String.valueOf(count));
    }


}
